//
//  SDateUtil.swift
//  niuguwang
//
//  Created by BrightLi on 2021/8/24.
//  Copyright © 2021年 taojinzhe. All rights reserved.
//

import Foundation

@objcMembers open class SDateUtil:NSObject
{
    static var _format = DateFormatter()
    //MARK: -时间转时间戳函数
    dynamic public class func timestampWith(date:String,format:String = "yyyy-MM-dd HH:mm:ss") -> Double
    {
        _format.dateFormat=format
        let timeZone = TimeZone.init(identifier: "Asia/Beijing")
        _format.timeZone = timeZone
        let last = _format.date(from: date)
        let timeStamp = last?.timeIntervalSince1970
        return timeStamp!
    }
    //MARK: -时间戳转时间函数
    dynamic public class func stringWith(timeStamp: Double,format:String = "yyyy-MM-dd HH:mm:ss")->String {
        //时间戳为毫秒级要 ／ 1000， 秒就不用除1000，参数带没带000
        let timeSta:TimeInterval = TimeInterval(timeStamp / 1000)
        let date = NSDate(timeIntervalSince1970: timeSta)
        //yyyy-MM-dd HH:mm:ss
        _format.dateFormat=format
        return _format.string(from: date as Date)
    }
    //MARK: - 根据后台时间戳返回几分钟前，几小时前，几天前
    dynamic public class func formatReduce(timeStamp: Double) -> String
    {
        //获取当前的时间戳
        let currentTime = Date().timeIntervalSince1970
        //时间戳为毫秒级要 ／ 1000， 秒就不用除1000，参数带没带000
        let timeSta:TimeInterval = TimeInterval(timeStamp)
        //时间差
        let reduceTime : TimeInterval = currentTime - timeSta
        //时间差小于60秒
        if reduceTime < 60 {
            return "刚刚"
        }
        //时间差大于一分钟小于60分钟内
        let mins = Int(reduceTime / 60)
        if mins < 60 {
            return "\(mins)分钟前"
        }
        let hours = Int(reduceTime / 3600)
        if hours < 24 {
            return "\(hours)小时前"
        }
        let days = Int(reduceTime / 3600 / 24)
        if days < 30 {
            return "\(days)天前"
        }
        //不满足上述条件---或者是未来日期-----直接返回日期
        let date = NSDate(timeIntervalSince1970: timeSta)
        //yyyy-MM-dd HH:mm:ss
        _format.dateFormat="yyyy年MM月dd日 HH:mm:ss"
        return _format.string(from: date as Date)
    }
    
    //MARK: - 格式化时间差
    dynamic public class func format(_ reduceTime: TimeInterval) -> String
    {
        let secs = Int(reduceTime) % 60
        //时间差小于60秒
        if reduceTime < 60 {
            return "\(secs)秒"
        }
        //时间差大于一分钟小于60分钟内
        let mins = Int(reduceTime / 60)
        if mins < 60 {
            return "\(mins)分钟\(secs)秒"
        }
        let hours = Int(reduceTime / 3600)
        if hours < 24 {
            return "\(hours)小时\(mins)分钟"
        }
        let days = Int(reduceTime / 3600 / 24)
        return "\(days)天\(hours)小时\(mins)分钟"
    }
}
